package com.test.multithread.callableTest;


//ThreadPool


import java.util.*;

public class ThreadPool extends Thread {
    
    /*
1. PoolTest(测试类)实现了Runnable接口，在构造函数中创建ThreadPool(线程池类)对象；
 执行任务runTask，将线程从Vector freeThreads转移到Vector inUseThreads，并调用PoolableThread的setTask。
2. ThreadPool在构造函数中，创建了10个PoolableThread(控制线程类)，start线程，并把线程加入Vector freeThreads里。
3. PoolableThread在开始创建的时候什么也不是做，进入阻塞状态；直到runTask里调用了setTask，notify自己让PoolTest线程 run;
 PoolTest run后即刻置null，将线程从Vector inUseThreads转移到Vector freeThreads。
4. PoolTest run的时候打印“线程名开始”，相隔2秒，打印“线程名结束”。*/

    private Vector freeThreads = new Vector();

    private Vector inUseThreads = new Vector();

    private static int INITIAL_SIZE = 10;



    public ThreadPool() {
        fillPool(INITIAL_SIZE);
    }



    private void fillPool(int poolsize) {
        for (int i = 0; i < poolsize; i++) {
            PoolableThread pt = new PoolableThread(this);
            pt.start();
            freeThreads.add(pt);
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
        }
    }



    public synchronized void runTask(Runnable task) {
        if (freeThreads.isEmpty()) {
            throw new RuntimeException("ALL threads are in use");
        }
        PoolableThread t = (PoolableThread) freeThreads.remove(0);
        inUseThreads.add(t);
        t.setTask(task);
    }

    synchronized void free(PoolableThread t) {
        inUseThreads.remove(t);
        freeThreads.add(t);
    }
}











//PoolTest

